package com.jiuli_shoppingpro.filter;


import com.alibaba.fastjson.JSONObject;
import com.jiuli_shoppingpro.utils.Result;
import com.jiuli_shoppingpro.utils.jwt.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                                        FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest ;
        HttpServletResponse resp = (HttpServletResponse) servletResponse ;

        String url = req.getRequestURL().toString();

        //判断该请求是否是登录操作
        if(url.contains("login") || url.contains("register")){
            //通过
            filterChain.doFilter(servletRequest, servletResponse);
            return ;
        }

        //判断是否包含令牌
        String jwt = req.getHeader("token");
        if(jwt == "" || jwt == null){
            //不能通过,生成一个错误数据返回给前端
            log.info("令牌不存在");
            Result erro = Result.error("NOT_LOGIN");
            /*手动转换成json格式的数据*/
            String notLogin = JSONObject.toJSONString(erro);
            resp.getWriter().println(notLogin);
            return;
        }

        //解析令牌
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌解析失败");
            //不能通过,生成一个错误数据返回给前端
            Result erro = Result.error("NOT_LOGIN");
            /*手动转换成json格式的数据*/
            String notLogin = JSONObject.toJSONString(erro);
            resp.getWriter().println(notLogin);
            return;
        }

        //通过
        filterChain.doFilter(servletRequest, servletResponse);
    }
}


























